<!DOCTYPE HTML>
<html lang="ch" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>实验4：协程与异步 - nudt os lab book (2023)</title>


        <!-- Custom HTML head -->
        
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="favicon.svg">
        <link rel="shortcut icon" href="favicon.png">
        <link rel="stylesheet" href="css/variables.css">
        <link rel="stylesheet" href="css/general.css">
        <link rel="stylesheet" href="css/chrome.css">
        <link rel="stylesheet" href="css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->

    </head>
    <body>
    <div id="body-container">
        <!-- Provide site root to javascript -->
        <script>
            var path_to_root = "";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script>
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script>
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script>
            var html = document.querySelector('html');
            var sidebar = null;
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            } else {
                sidebar = 'hidden';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded affix "><li class="part-title">操作系统实验指南</li><li class="chapter-item expanded "><a href="lab_0.html"><strong aria-hidden="true">1.</strong> 准备：实验环境搭建</a></li><li class="chapter-item expanded "><a href="lab_1.html"><strong aria-hidden="true">2.</strong> 实验1：向Framebuffer中打印字符</a></li><li class="chapter-item expanded "><a href="lab_2.html"><strong aria-hidden="true">3.</strong> 实验2：异常处理和硬件中断</a></li><li class="chapter-item expanded "><a href="lab_3.html"><strong aria-hidden="true">4.</strong> 实验3：内存管理</a></li><li class="chapter-item expanded "><a href="lab_4.html" class="active"><strong aria-hidden="true">5.</strong> 实验4：协程与异步</a></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">nudt os lab book (2023)</h1>

                    <div class="right-buttons">
                        <a href="print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script>
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="实验4"><a class="header" href="#实验4">实验4：</a></h1>
<ol>
<li>
<p>掌握协程执行的方法原理，掌握实现键盘事件流协程的方法。参考<a href="https://os.phil-opp.com/">blog_os</a>教程的<a href="https://os.phil-opp.com/async-await">Async/Await</a>章节，理解<code>kernel/src/task/executor.rs</code>和<code>kernel/src/task/keyboard.rs</code>两个文件中的代码。</p>
</li>
<li>
<p>模仿实现鼠标事件流协程。仿照<code>kernel/src/task/keyboard.rs</code>文件中实现键盘事件流协程的方法，新建源码文件<code>kernel/src/task/mouse.rs</code>，并实现鼠标事件流协程。</p>
</li>
</ol>
<blockquote>
<p>提示</p>
<ul>
<li>仿照<code>print_keypresses</code>实现<code>print_mousemovements</code>异步函数，负责执行<code>kernel/src/driver/idt.rs</code>文件中针对鼠标中断的处理逻辑。</li>
<li>仿照<code>kernel/src/main.rs</code>文件中添加<code>print_keypresses</code>任务的方法，添加<code>print_mousemovements</code>任务。</li>
</ul>
</blockquote>
<ol start="3">
<li>编写协程。实现一个sleep函数，可在给定数量的时钟中断后输出一个字符串，等待期间不占用CPU，鼠标可以正常使用。</li>
</ol>
<blockquote>
<p>提示</p>
<ul>
<li>定义<code>AtomicUsize</code>类型全局变量<code>TIMER_TICK</code>记录时钟数，和<code>AtomicWaker</code>类型全局变量<code>TIMER_WAKER</code>唤醒器。在每次时钟中断发生时改变<code>TIMER_TICK</code>，达到预期时间后调用<code>TIMER_WAKER.wake()</code>。</li>
<li>编写<code>SleepFuture</code>，实现<code>Future trait</code>，其中<code>poll</code>函数中<code>TIMER_TICK</code>达到预期时返回<code>Ready</code>，否则注册唤醒器<code>TIMER_WAKER.register(&amp;cx.waker());</code>后返回<code>Pending</code>。</li>
<li>定义异步函数<code>sleep</code>，接收参数<code>睡眠的时钟周期数</code>，函数中创建<code>SleepFuture</code>对象<code>sleep_future</code>，之后执行<code>sleep_future.await</code>，等待结束后打印任意信息。</li>
</ul>
</blockquote>
<ol start="4">
<li>实现一个简单的shell，可以处理来自键盘输入的字符，支持以下命令：</li>
</ol>
<ul>
<li><code>clear</code>: 清屏</li>
<li><code>echo hi</code>: 打印字符串hi</li>
<li><code>export ENV=value</code>: 设置环境变量</li>
<li><code>env</code>: 打印全部环境变量</li>
<li><code>sleep 20 echo hi</code>: 睡眠20个时钟周期后打印hi
<ul>
<li>睡眠支持两种模式，根据环境变量使用相应的模式：
<ul>
<li>同步模式（默认使用）：死循环等待给定时钟周期后打印</li>
<li>异步模式（设置环境变量<code>MODE=async</code>后使用）：异步睡眠给定时钟周期后打印</li>
</ul>
</li>
</ul>
</li>
</ul>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="lab_3.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>


                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="lab_3.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>

            </nav>

        </div>

        <!-- Livereload script (if served using the cli tool) -->
        <script>
            const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsAddress = wsProtocol + "//" + location.host + "/" + "__livereload";
            const socket = new WebSocket(wsAddress);
            socket.onmessage = function (event) {
                if (event.data === "reload") {
                    socket.close();
                    location.reload();
                }
            };

            window.onbeforeunload = function() {
                socket.close();
            }
        </script>



        <script>
            window.playground_copyable = true;
        </script>


        <script src="elasticlunr.min.js"></script>
        <script src="mark.min.js"></script>
        <script src="searcher.js"></script>

        <script src="clipboard.min.js"></script>
        <script src="highlight.js"></script>
        <script src="book.js"></script>

        <!-- Custom JS scripts -->


    </div>
    </body>
</html>
